<template>
  <div>
    <a-spin v-if="initLoading" :spinning="initLoading"> </a-spin>
    <a-select
      v-show="!initLoading"
      show-search
      optionFilterProp="showLabel"
      option-label-prop="label"
      :dropdownMatchSelectWidth="false"
      :mode="
        record.options.type == this.eipZeroCodeControlCorrelationType.multiple
          ? 'multiple'
          : ''
      "
      :disabled="record.options.disabled || parentDisabled"
      :size="record.options.size"
      :placeholder="record.options.placeholder"
      :allowClear="record.options.clearable"
      @blur="clearKey"
      @focus="focus"
      @popupScroll="popupScroll"
      @change="change"
      @search="search"
      v-model="data"
    >
      <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
        <a-divider style="margin: 4px 0" v-if="record.options.canAdd" />
        <div
          v-if="record.options.canAdd"
          @click="add"
          style="cursor: pointer"
          class="padding-left-xs padding-bottom-xs"
        >
          <a-button type="primary" size="small"
            ><a-icon type="plus" /> 新增{{ record.label }}</a-button
          >
        </div>
      </div>
      <a-select-option
        v-for="item in options"
        :key="item.value"
        :value="item.value"
        :label="item.label"
        :showLabel="item.showLabel"
      >
        <div style="border-bottom: 1px solid rgba(0, 0, 0, 0.06)">
          <div class="title">
            {{ item.label }}
          </div>
          <div style="margin-left: -7px">
            <div
              v-if="index != 0"
              v-for="(litem, index) in item.labels"
              :key="index"
              class="item ellipsis"
            >
              <div v-if="litem.column && litem.column.options.optionsColor">
                <a-button
                  :title="litemcolor.label"
                  v-for="(litemcolor, litemindex) in litem.label"
                  :key="litemindex"
                  :style="{
                    'background-color': litemcolor.color,
                    color: '#fff',
                    'font-size': '12px',
                    border: 'none',
                  }"
                  shape="round"
                  size="small"
                >
                  {{ litemcolor.label }}</a-button
                >
              </div>
              <div
                v-if="
                  litem.column &&
                  litem.column.type == [eipZeroCodeControl.correlation]
                "
              >
                <a-button
                  :title="label"
                  v-for="(label, litemindex) in litem.label"
                  :key="litemindex"
                  style="
                    background-color: rgba(0, 100, 240, 0.08);
                    border-radius: 3px;
                    padding: 0 10px;
                  "
                  size="small"
                >
                  {{ label }}</a-button
                >
              </div>

              <div
                v-if="
                  litem.column &&
                  litem.column.type == [eipZeroCodeControl.switch]
                "
              >
                <a-switch v-model="litem.label" disabled></a-switch>
              </div>

              <span v-else :title="litem.label"> {{ litem.label }} </span>
            </div>
          </div>
        </div>
      </a-select-option>

      <a-select-option key="" value="" v-if="!isEnd">
        <div style="text-align: center">
          <a-spin :spinning="true"></a-spin>
        </div>
      </a-select-option>
    </a-select>

    <!-- 表单 -->
    <worksheet-run
      ref="worksheetRun"
      v-if="worksheetRun.visible"
      :visible.sync="worksheetRun.visible"
      :options="{
        rowId: worksheetRun.rowId,
        rowIds: [worksheetRun.rowId],
        zeroCodeId: record.options.zeroCodeId,
        mode: eipZeroCodeWorkSheetMode.add,
        from: {
          zeroCodeId: worksheet.zeroCodeId,
          key: record.key, //来源控件
          rowId: worksheet.rowId, //来源数据RowId
        },
      }"
      @ok="worksheetRunOk"
    ></worksheet-run>
  </div>
</template>
<script>
import {
  findById,
  businessDataById,
  findCorrelationFilter,
  findCorrelationDefault,
  findCorrelationDefaultAdd,
} from "@/services/system/zerocode/run/edit";
import worksheetRun from "@/pages/system/zerocode/run/worksheet";
import { newGuid } from "@/utils/util";
export default {
  data() {
    return {
      initLoading: false, //初始化是否加载效果
      selectLoading: false, //选择加载效果
      isEnd: false, //是否加载到了最后
      isChange: false, //是否已选择过
      options: [], //下拉选项
      data: undefined, //选中数据
      size: 20, //分页数量
      current: 1, //第几页
      key: "", //输入关键字
      systemZeroCodeData: null, //关联表配置
      allColumns: [], //显示所有配置
      timeout: null, //超时变量
      optionsWatch: [],

      //编辑组件
      worksheetRun: {
        rowId: newGuid(),
        visible: false,
      },
    };
  },
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
    worksheetRun,
  },
  props: ["record", "value", "formValue", "parentDisabled", "worksheet"],
  watch: {
    value(value) {
      if (value) {
        this.data = value;
      }
    },
    "record.options.options": {
      handler: function (val, oldVal) {
        this.optionsWatch = val;
      },
      deep: true,
    },
    "record.options.zeroCodeId": {
      handler: function (val, oldVal) {
        if (val != oldVal) {
          this.getDefault();
        }
      },
      deep: true,
    },
  },
  created() {
    this.getDefault();
  },
  methods: {
    /**
     * 新增
     */
    add() {
      this.worksheetRun.visible = true;
    },
    /**
     *
     */
    worksheetRunOk(result) {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      for (let index = 0; index < showColumns.length; index++) {
        const item = showColumns[index];
        data[item.key] = result.data[item.key];
      }
      this.grid.data.push({
        ...data,
        RowId: result.data.RowId,
      });
      //数据源获取
      this.handleInput();
      this.worksheetRun.visible = false;
    },

    /**
     * 获取数据
     */
    getDefault() {
      let that = this;
      //编辑并且有值
      if (that.record.options.zeroCodeId) {
        this.initLoading = true;
        this.selectLoading = true;
        findById(that.record.options.zeroCodeId).then((systemZeroCodeData) => {
          that.systemZeroCodeData = systemZeroCodeData;
          //编辑重新加载数据
          switch (that.worksheet.mode) {
            case that.eipZeroCodeWorkSheetMode.edit:
              if (that.value) {
                findCorrelationDefault({
                  zeroCodeId: that.worksheet.zeroCodeId,
                  key: that.record.key,
                  rowId: that.worksheet.rowId,
                }).then((resultTable) => {
                  that.setOptions(resultTable);
                });
              } else {
                that.closeLoading();
              }
              break;
            case that.eipZeroCodeWorkSheetMode.button:
              //是否选择的多个
              let button = that.worksheet.from.button;
              if (
                button.form.write ==
                that.eipZeroCodeFormSettingButtonFormWrite.field
              ) {
                findCorrelationDefault({
                  zeroCodeId: that.worksheet.zeroCodeId,
                  key: that.record.key,
                  rowId: that.worksheet.from.rowId,
                }).then((resultTable) => {
                  that.setOptions(resultTable);
                });
              }
              //当前记录，填写关联
              else if (
                button.form.write ==
                that.eipZeroCodeFormSettingButtonFormWrite.correlation
              ) {
                businessDataById({
                  zeroCodeId: that.record.options.zeroCodeId,
                  id: that.worksheet.from.rowId,
                }).then((resultTable) => {
                  if (resultTable.data) {
                    that.data = that.worksheet.from.rowId;
                    that.record.options.disabled = true;
                    let data = {
                      RowId: that.worksheet.from.rowId,
                    };
                    data = resultTable.data;
                    that.setOptions({
                      code: resultTable.code,
                      msg: resultTable.msg,
                      data: {
                        data: [data],
                      },
                    });
                    that.change();
                  } else {
                    that.closeLoading();
                  }
                });
              }
              break;
            case that.eipZeroCodeWorkSheetMode.add:
              //判断是否有来源,从关联表来，直接赋予了默认值
              if (
                that.worksheet.from &&
                that.worksheet.from.zeroCodeId &&
                that.record.options.twoway.is &&
                that.worksheet.from.key == that.record.options.twoway.key
              ) {
                businessDataById({
                  zeroCodeId: that.record.options.zeroCodeId,
                  id: that.worksheet.from.rowId,
                }).then((resultTable) => {
                  that.data = that.worksheet.from.rowId;
                  that.record.options.disabled = true;
                  //一个新增记录再次关联一个新增
                  let data = {
                    RowId: that.worksheet.from.rowId,
                  };
                  if (resultTable.data == null) {
                    var title = JSON.parse(
                      that.systemZeroCodeData.data.publicJson
                    ).config.title;
                    data[title] = "当前记录";
                  } else {
                    data = resultTable.data;
                  }
                  that.setOptions({
                    code: resultTable.code,
                    msg: resultTable.msg,
                    data: {
                      data: [data],
                    },
                  });
                  that.change();
                });
              } else {
                switch (that.record.options.defaultValueConfig.type) {
                  case that.eipZeroCodeDefaultType.field:
                    findCorrelationDefaultAdd({
                      zeroCodeId: that.worksheet.zeroCodeId,
                      key: that.record.key,
                    }).then((resultTable) => {
                      that.setOptions(resultTable);
                    });
                    break;
                  case that.eipZeroCodeDefaultType.worksheet:
                    that.setOptions(this.optionsWatch);
                    break;
                  default:
                    that.closeLoading();
                    break;
                }
              }
              break;
            default:
              that.closeLoading();
              break;
          }
        });
      }
    },

    closeLoading() {
      this.initLoading = false;
      this.selectLoading = false;
    },

    /**
     * 查询数据
     */
    focus() {
      let that = this;
      this.options = [];
      this.current = 1;
      that.selectLoading = true;
      if (that.systemZeroCodeData) {
        that.debounce(() => {
          that.getData();
        });
      } else {
        findById(this.record.options.zeroCodeId).then((systemZeroCodeData) => {
          that.systemZeroCodeData = systemZeroCodeData;
          that.debounce(() => {
            that.getData();
          });
        });
      }
    },
    /**
     * 关键字
     * @param e
     */
    search(e) {
      this.key = e;
      this.focus();
    },

    /**
     * 防抖
     * @param callback
     * @param delay
     */
    debounce(callback, delay = 200) {
      if (this.timeout) {
        clearTimeout(this.timeout);
      }

      this.timeout = setTimeout(() => {
        callback();
      }, delay);
    },

    /**
     * 获取数据
     */
    getData(value) {
      let that = this;
      var filters = that.analysisFilter(this.record.options.records.filters);
      that.analysisFilterKey(filters, this.record.options.columns);
      findCorrelationFilter({
        zeroCodeId: this.worksheet.zeroCodeId,
        formValue: that.formValue,
        filters: JSON.stringify(filters),
        size: that.size,
        current: that.current,
        value: value,
        key: that.record.key,
        rowId: that.worksheet.rowId,
      }).then((resultTable) => {
        that.setOptions(resultTable);
      });
    },

    /**
     * 赋予值
     */
    setOptions(resultTable) {
      let that = this;
      var title = JSON.parse(that.systemZeroCodeData.data.publicJson).config
        .title;
      var correlationColumnJson = JSON.parse(
        that.systemZeroCodeData.data.columnJson
      );

      let dynamicData = [];
      resultTable.data.data.forEach((res) => {
        var labels = [];
        var showLabels = [];
        that.record.options.columns.forEach((key) => {
          if (res[key] != null) {
            switch (key) {
              case "CreateUser":
                showLabels.push(res[key + "Name"]);
                labels.push({
                  column: null,
                  label: res[key + "Name"],
                });
                break;
              default:
                //判断类型
                var findColumn = that.$utils.find(
                  correlationColumnJson,
                  (f) => f.key == key
                );
                if (findColumn) {
                  switch (findColumn.type) {
                    case that.eipZeroCodeControl.radio:
                    case that.eipZeroCodeControl.select:
                    case that.eipZeroCodeControl.checkbox:
                      var values = JSON.parse(res[key]);
                      //判断是否有颜色选项
                      var labelsOptions = [];
                      values.forEach((v) => {
                        var option = that.$utils.find(
                          findColumn.options.options,
                          (f) => f.value == v
                        );
                        if (option) {
                          showLabels.push(option.label);
                          labelsOptions.push(option);
                        }
                      });
                      labels.push({
                        column: findColumn,
                        label: labelsOptions,
                      });
                      break;
                    case that.eipZeroCodeControl.correlation:
                      var values = JSON.parse(res[key]);
                      var labelsOptions = [];
                      values.forEach((v) => {
                        showLabels.push(v.Title);
                        labelsOptions.push(v.Title);
                      });
                      labels.push({
                        column: findColumn,
                        label: labelsOptions,
                      });
                      break;
                    case that.eipZeroCodeControl.switch:
                      labels.push({
                        column: findColumn,
                        label: res[key],
                      });
                      break;
                    default:
                      showLabels.push(res[key]);
                      labels.push({
                        column: null,
                        label: res[key],
                      });
                      break;
                  }
                } else {
                  showLabels.push(res[key]);
                  labels.push({
                    column: null,
                    label: res[key],
                  });
                }
                break;
            }
          }
        });
        dynamicData.push({
          label: res[title],
          showLabel: showLabels.join("|"),
          labels: labels,
          value: res["RowId"],
        });
      });
      that.options = that.options.concat(dynamicData);
      //判断是否已加载到最后
      if (that.options.length >= resultTable.data.count) {
        that.isEnd = true;
      }
      that.initLoading = false;
      that.selectLoading = false;
      //设置值
      that.record.options.options = that.options;
    },

    /**
     * 如果有关键词
     */
    analysisFilterKey(filters, allColumns) {
      if (this.key) {
        var selectFilters = {
          groupOp: "OR",
          rules: [],
        };
        allColumns.forEach((ditem) => {
          selectFilters.rules.push({
            field: ditem,
            op: "cn",
            data: this.key,
          });
        });
        filters.groups.push(selectFilters);
      }
    },

    /**
     * 解析filter，返回替换后表达式
     */
    analysisFilter(filter) {
      let that = this;
      let copyFilters = this.$utils.clone(filter, true);
      let filters = {
        groupOp: copyFilters.groupOp,
        rules: [],
        groups: [],
      };
      // 递归遍历控件树
      const traverseRule = (array, filters) => {
        array.forEach((element) => {
          switch (element.type) {
            case "correlation":
              filters.rules.push({
                field: element.field,
                op: element.op,
                data: that.analysisFilterData({
                  type: "correlation",
                  data: element.data,
                }),
              });

              break;
            default:
              filters.rules.push({
                field: element.field,
                op: element.op,
                data: that.analysisFilterData(element),
              });
              break;
          }
        });
      };
      traverseRule(copyFilters.rules, filters);

      const traverseGroup = (array, filters) => {
        array.forEach((element) => {
          var group = {
            groupOp: element.groupOp,
            rules: [],
            groups: [],
          };

          element.rules.forEach((rule) => {
            switch (rule.type) {
              case "correlation":
                if (rule.data.length > 0) {
                  var selectFilters = {
                    groupOp: "OR",
                    rules: [],
                  };
                  //循环值
                  rule.data.forEach((ditem) => {
                    selectFilters.rules.push({
                      field: rule.field.replace("_Txt", ""),
                      op: rule.op,
                      data: that.analysisFilterData({
                        type: "correlation",
                        data: ditem,
                      }),
                    });
                  });
                  group.groups.push(selectFilters);
                }
                break;
              default:
                group.rules.push({
                  field: rule.field,
                  op: rule.op,
                  data: that.analysisFilterData(rule),
                });
                break;
            }
          });

          filters.groups.push(group);

          if (element.groups.length > 0) {
            traverseGroup(element.groups, filters);
          }
        });
      };
      traverseGroup(copyFilters.groups, filters);
      return filters;
    },

    /**
     * 解析数据
     * @param {*} data
     */
    analysisFilterData(rule) {
      var that = this;
      var column = this.$utils.find(that.columnJson, (f) => f.key == rule.data);
      switch (rule.type) {
        case "input":
          return rule.data;
        case "correlationRecord":
          return this.formValue[column.model];
      }
    },
    /**
     * 下拉列表滚动时的回调
     * @param {*} e
     */
    popupScroll(e) {
      var that = this;
      const { target } = e;
      const { scrollTop, scrollHeight, clientHeight } = target;
      if (scrollTop + 2 + clientHeight >= scrollHeight) {
        if (!this.isEnd) {
          this.current += 1;
          this.selectLoading = true;
          that.debounce(() => {
            that.getData();
          });
        }
      }
    },

    /**
     * 下拉改变
     */
    change() {
      this.isChange = true;
      this.clearKey();
      this.$emit("change", this.data);
    },

    /**
     * 清除关键字
     */
    clearKey() {
      this.key = null;
    },
  },
};
</script>
<style lang="less" scoped>
.title {
  color: rgb(51, 51, 51);
  font-weight: bold;
  line-height: 1.5;
  margin-bottom: 4px;
}

.item {
  -webkit-box-orient: vertical;
  border-right: 1px solid #9e9e9e;
  color: #757575;
  display: inline-block;
  height: 1.8em !important;
  line-height: 1.6em;
  overflow: hidden;
  max-width: 200px;
  padding: 0 7px;
  text-overflow: ellipsis;
  word-break: break-all;
}
.item:last-child {
  border-right: none;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: top;
  white-space: nowrap;
}
</style>
